package com.irany.util;

import cn.hutool.setting.dialect.PropsUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shujian.ou
 * @since 2021/5/17 0017 15:27
 */
public class SeleniumUtils {

    private static final Map<String, WebDriver> DRIVERS = new HashMap<String, WebDriver>(6);

    public static WebDriver getDriver(String driverKey) {
        return getDriver(driverKey, null);
    }

    public static WebDriver getDriver(String driverKey, ChromeOptions options) {
        WebDriver driver = DRIVERS.get(driverKey);
        if (driver == null) {
            System.setProperty("webdriver.chrome.driver", PropsUtil.get("app").getStr("webdriver.chrome.driver"));
            if (options == null) {
                driver = new ChromeDriver();
            } else {
                driver = new ChromeDriver(options);
            }
        }
        DRIVERS.put(driverKey, driver);
        return driver;
    }

    public static void removeDriver(String driverKey) {
        DRIVERS.remove(driverKey);
    }

    /**
     * 判断某个元素是否存在
     */
    public static boolean existElement(WebDriver driver, By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 打开一个新页面并切换到页面
     */
    public static void openNewWindowAndSwitch(WebDriver driver, String url) {
        openNewWindow(driver, url);
        driver.switchTo().window(new ArrayList<>(driver.getWindowHandles()).get(driver.getWindowHandles().size() - 1));
    }

    /**
     * 打开一个新页面
     */
    public static void openNewWindow(WebDriver driver, String url) {
        JavascriptExecutor jsDriver = (JavascriptExecutor) driver;
        jsDriver.executeScript("window.open('" + url + "')");
    }

}
